﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace CQFQW
{
    /// <summary>
    /// 获取 文章
    /// </summary>
    public class GetContentUrl
    {

        /// <summary>
        /// 更多 文章 list地址
        /// </summary>
         GetUrl listUrl = null;

        /// <summary>
        /// 文章的地址 的地址
        /// </summary>
        public IList<string> contentUrlList;

        /// <summary>
        /// 获取文章是否结束了
        /// </summary>
        public bool getContentUrlEndLoop = false;

        public event SetTextCallback setText;
        /// <summary>
        /// 是否继续
        /// </summary>
       public bool isStop = false;

        public GetContentUrl(GetUrl getUrl)
        {
            contentUrlList = new List<string>();
            this.listUrl = getUrl;
        }

        /// <summary>
        /// 获取文章 编号
        /// url = string.Format("http://chaoju.csfqw.com/DiggAndTread.aspx?nid={0}&FlagName=Tread&articletitle", password);
        /// </summary>
        public void GetContentIdUrl()
        {
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;
            while (!isStop && !listUrl.IsEndLoop)
            {
                string url = "";
                string result = "";
                try
                {
                    url = listUrl.GetAdress();
                    if (url==null)
                    {
                        break;
                    }
                    result = wc.DownloadString(url);
                    Match[] ids = new MatchData("<a href=(\"|')content-", "(.|\n)*?.html(\"|')", result).Matches(RegexOptions.IgnoreCase);
                    foreach (var item in ids)
                    {
                        string id = new MatchData("<a href=(\"|')content-", ".html(\"|')", item.Value).Match(RegexOptions.IgnoreCase);
                        contentUrlList.Add(id);
                    }
                }
                catch (Exception e)
                {
                    Thread.Sleep(2000);
                    if (setText != null)
                    {
                        setText("error:url="+url+ "&message:"+e.Message);
                    }
                }

            }
            lock (this)
            {
                if (getContentUrlEndLoop == false)
                {
                    getContentUrlEndLoop = true;
                    if (setText != null)
                    {
                        Thread.Sleep(5000);
                        setText("结束 获取文章编号。数量:" + contentUrlList.Count);
                    }
                }
            }

        }
    }
}
